package com.xyzisme76.application;

import com.xyzisme76.dao.CourseDao;
import com.xyzisme76.dao.ScDao;
import com.xyzisme76.dao.StudentDao;
import com.xyzisme76.pojo.Course;
import com.xyzisme76.pojo.Sc;
import com.xyzisme76.pojo.Student;
import com.xyzisme76.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

public class InfoIndex {
    final int WIDTH = 800;
    final  int HEIGHT = 700;
    public void AllInDex(){
        AtomicInteger flagChange = new AtomicInteger(1);

        JFrame jf = new JFrame("InfoIndex");

        jf.setVisible(true);

        jf.setSize(new Dimension(WIDTH,HEIGHT));
        //jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // 创建内容面板，使用边界布局
        //JPanel panel = new JPanel(new BorderLayout());
        // 所在位置 居中
        jf.setLocationRelativeTo(null);
        //设置背景图片
        JPanel jp = new JPanel() {
            protected void paintComponent(Graphics g) {
                try {
                    Image bg = ImageIO.read(new File(
                            "src/main/java/com/xyzisme76/application/images/page3.PNG"));
                    g.drawImage(bg, 0, 0, getWidth(), getHeight(), null);
                }catch(IOException e) {
                    e.printStackTrace();
                }
            }
        };
        //初始化显示学生信息表，后期会刷新表单

        // 表头（列名）


        List<Student> students = StudentInfo.studentsGet();
        Iterator var4 = students.iterator();
        int forNut = students.size();
        Object[] columnNames = {"学号", "姓名", "性别", "年龄", "所在系"};
        Object[][] rowData = new Object[forNut][5];// 表格所有行数据
        int j = 0;
        while(var4.hasNext()) {
            Student student = (Student)var4.next();
            rowData[j][0] = student.getSno();
            rowData[j][1] = student.getName();
            rowData[j][2] = student.getSex();
            rowData[j][3] = student.getAge();
            rowData[j][4] = student.getDept();
            j++;
        }
        // 创建 表格模型，指定 所有行数据 和 表头
        TableModel tableModel = new DefaultTableModel(rowData, columnNames);

        // 使用 表格模型 创建 表格
        JTable table = new JTable(tableModel);
        JButton jCourse = new JButton("课程表");
        JButton jSc = new JButton("成绩表");
        JButton jTittle = new JButton("学生信息表");
        JButton addButton = new JButton("添加");
        JButton chgButton = new JButton("修改");
        JButton delButton = new JButton("删除");
        JTextField field1 = new JTextField(12);
        JTextField field2 = new JTextField(12);
        JTextField field3 = new JTextField(12);
        JTextField field4 = new JTextField(12);
        JTextField field5 = new JTextField(12);


        // 使用 表格模型 创建 行排序器（TableRowSorter 实现了 RowSorter）
        RowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>(tableModel);

        // 给 表格 设置 行排序器
        table.setRowSorter(rowSorter);

        // 把 表头 添加到容器顶部（使用普通的中间容器添加表格时，表头 和 内容 需要分开添加）
        jp.add(table.getTableHeader());
        // 把 表格内容 添加到容器中心
        jp.add(table);
        jp.add(jTittle);
        //jp.add(jStudent);
        jp.add(jCourse);
        jp.add(jSc);
        jp.setLayout(null);
        jp.add(field1);
        jp.add(field2);
        jp.add(field3);
        jp.add(field4);
        jp.add(field5);
        jp.add(addButton);
        jp.add(delButton);
        jp.add(chgButton);


        addButton.setForeground(Color.DARK_GRAY);
        addButton.setBackground(Color.white);
        addButton.setFont(new Font("微软雅黑", Font.BOLD, 15));
        delButton.setForeground(Color.DARK_GRAY);
        delButton.setBackground(Color.white);
        delButton.setFont(new Font("微软雅黑", Font.BOLD, 15));
        chgButton.setForeground(Color.DARK_GRAY);
        chgButton.setBackground(Color.white);
        chgButton.setFont(new Font("微软雅黑", Font.BOLD, 15));


        jCourse.setForeground(Color.LIGHT_GRAY);
        jCourse.setFont(new Font("微软雅黑", Font.BOLD, 30));
        jTittle.setForeground(Color.DARK_GRAY);
        jTittle.setFont(new Font("微软雅黑", Font.BOLD, 30));
        jSc.setForeground(Color.LIGHT_GRAY);
        jSc.setFont(new Font("微软雅黑", Font.BOLD, 30));



        jCourse.setBackground(Color.white);
        jCourse.setMargin(new Insets(0,0,0,0));//将边框外的上下左右空间设置为0
        jCourse.setBorderPainted(false);//不打印边框
        jCourse.setFocusPainted(false);//除去焦点的框
        jCourse.setContentAreaFilled(false);//除去默认的背景填充
        jCourse.addActionListener(e -> {
            flagChange.set(2);
            List<Course> courseList = CourseInfo.CourseGet();
            Iterator var5 = courseList.iterator();
            int forNut2 = courseList.size();
            Object[] columnNames2 = {"课程号", "课程名", "学分", "教师"};
            Object[][] rowData2 = new Object[forNut][4];// 表格所有行数据
            int i = 0;
            while(var5.hasNext()) {
                Course course = (Course) var5.next();
                rowData2[i][0] = course.getCno();
                rowData2[i][1] = course.getCname();
                rowData2[i][2] = course.getCredit();
                rowData2[i][3] = course.getTeacher();
                i++;
            }
            TableModel tableModels2 = new DefaultTableModel(rowData2, columnNames2);
            table.setModel(tableModels2);
            //table.setEnabled(true);

            jCourse.setForeground(Color.DARK_GRAY);
            jTittle.setForeground(Color.LIGHT_GRAY);
            jSc.setForeground(Color.LIGHT_GRAY);
        });

        jTittle.setBackground(Color.white);
        jTittle.setMargin(new Insets(0,0,0,0));//将边框外的上下左右空间设置为0
        jTittle.setBorderPainted(false);//不打印边框
        jTittle.setFocusPainted(false);//除去焦点的框
        jTittle.setContentAreaFilled(false);//除去默认的背景填充
        jTittle.addActionListener(e -> {
            flagChange.set(1);
            TableModel tableModels = new DefaultTableModel(rowData, columnNames);

            // 使用 表格模型 创建 表格
            table.setModel(tableModels);
            table.setEnabled(true);
            jTittle.setForeground(Color.DARK_GRAY);
            jCourse.setForeground(Color.LIGHT_GRAY);
            jSc.setForeground(Color.LIGHT_GRAY);
        });

        jSc.setBackground(Color.white);
        jSc.setMargin(new Insets(0,0,0,0));//将边框外的上下左右空间设置为0
        jSc.setBorderPainted(false);//不打印边框
        jSc.setFocusPainted(false);//除去焦点的框
        jSc.setContentAreaFilled(false);//除去默认的背景填充
        jSc.addActionListener(e -> {
            flagChange.set(3);
            List<Sc> scList = ScInfo.ScGet();
            Iterator var6 =scList.iterator();
            int forNut3 = scList.size();
            Object[] columnNames3 = {"学生号", "课程号", "成绩"};
            Object[][] rowData3 = new Object[forNut3][3];// 表格所有行数据
            int f = 0;
            while(var6.hasNext()) {
                Sc sc = (Sc) var6.next();
                rowData3[f][0] = sc.getSno();
                rowData3[f][1] = sc.getCno();
                rowData3[f][2] = sc.getGrade();
                f++;
            }
            TableModel tableModels3 = new DefaultTableModel(rowData3, columnNames3);
            table.setModel(tableModels3);
            jSc.setForeground(Color.DARK_GRAY);
            jCourse.setForeground(Color.LIGHT_GRAY);
            jTittle.setForeground(Color.LIGHT_GRAY);
        });

        delButton.addActionListener(e->{
            int index = table.getSelectedRow();
            int indexGet = (int) table.getValueAt(index,0);
            System.out.println(indexGet);
            if(flagChange.get() == 1 ) {
                SqlSession sqlSession = MybatisUtil.getSqlSession();
                StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
                studentDao.deleteStudentById(String.valueOf(indexGet));
                JOptionPane.showMessageDialog(null, "删除成功！");
                sqlSession.commit();
                sqlSession.close();
                jf.dispose(); //关闭当前页面并且刷新；
                new InfoIndex();
            }
            if(flagChange.get() == 2){
                SqlSession sqlSession = MybatisUtil.getSqlSession();
                CourseDao courseDao = sqlSession.getMapper(CourseDao.class);
                courseDao.deleteCourse(String.valueOf(indexGet));
                JOptionPane.showMessageDialog(null, "删除成功！");
                sqlSession.commit();
                sqlSession.close();
                jf.dispose(); //关闭当前页面并且刷新；
                new InfoIndex();
            }
//            if(flagChange.get() == 3){
//                SqlSession sqlSession = MybatisUtil.getSqlSession();
//                ScDao scDao = sqlSession.getMapper(ScDao.class);
//                scDao.deleteSc(String.valueOf(indexGet),String.valueOf(indexGet1));
//                JOptionPane.showMessageDialog(null, "删除成功！");
//                jf.dispose(); //关闭当前页面并且刷新；
//                new InfoIndex();
//                sqlSession.commit();
//                sqlSession.close();
//            }
        });




        addButton.addActionListener(e->{
            if(flagChange.get() == 1 ){  //如果值为1 为学生表添加
                SqlSession sqlSession = MybatisUtil.getSqlSession();
                StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
                studentDao.addStudent(new Student(Integer.parseInt(field1.getText()),field2.getText()
                                     ,field3.getText(),field4.getText(),field5.getText()));
                sqlSession.commit();
                sqlSession.close();
                JOptionPane.showMessageDialog(null,"添加成功！");
                jf.dispose();
                new InfoIndex();
            }
            if(flagChange.get() == 2 ){

                SqlSession sqlSession = MybatisUtil.getSqlSession();
                CourseDao cousreDao = sqlSession.getMapper(CourseDao.class);
                cousreDao.addCourse(new Course(field1.getText(),field2.getText(),
                                    Integer.parseInt(field3.getText()),field4.getText()));
                sqlSession.commit();
                sqlSession.close();
                JOptionPane.showMessageDialog(null,"添加成功！");
                jf.dispose();
                new InfoIndex();
            }
            if(flagChange.get() == 3 ){
                SqlSession sqlSession = MybatisUtil.getSqlSession();
                ScDao scDao = sqlSession.getMapper(ScDao.class);
                scDao.insertSc(new Sc(field1.getText(),field2.getText(),Integer.parseInt(field3.getText())));
                sqlSession.commit();
                sqlSession.close();
                JOptionPane.showMessageDialog(null,"添加成功！");
                jf.dispose();
                new InfoIndex();
            }
        });

        chgButton.addActionListener(e->{
            if(flagChange.get() == 1){
                if(!Objects.equals(field3.getText(), "男") || !Objects.equals(field3.getText(), "女")) {
                    JOptionPane.showMessageDialog(null,"修改性别失败！");
                }
                else{
                    ChgStudent.chgStudent(new Student(Integer.parseInt(field1.getText()),field2.getText()
                            ,field3.getText(),field4.getText(),field5.getText()));
                    JOptionPane.showMessageDialog(null,"修改成功！");
                    jf.dispose();
                    new InfoIndex();
                }
            }
            if(flagChange.get() == 2){
                ChgCourse.chgCourse(new Course(field1.getText(),field2.getText()
                        ,Integer.parseInt(field3.getText()),field4.getText()));
                JOptionPane.showMessageDialog(null,"修改成功！");
                jf.dispose();
                new InfoIndex();
            }
            if(flagChange.get() == 3){
                ChgSc.chgSc(new Sc(field1.getText(),field2.getText()
                        ,Integer.parseInt(field3.getText())));
                JOptionPane.showMessageDialog(null,"修改成功！");
                jf.dispose();
                new InfoIndex();
            }
        });

        field1.setBounds(100,80,100,30);
        field2.setBounds(210,80,100,30);
        field3.setBounds(320,80,100,30);
        field4.setBounds(430,80,100,30);
        field5.setBounds(540,80,100,30);
        addButton.setBounds(100,130,100,30);
        delButton.setBounds(210,130,100,30);
        chgButton.setBounds(320,130,100,30);
        table.setBounds(100, 220, 500, 600);
        table.getTableHeader().setBounds(100,190,500,30);
        jTittle.setBounds(100,10,190,60);
        jCourse.setBounds(300,10,150,60);
        jSc.setBounds(470,10,130,60);
        jf.setContentPane(jp);

        jf.setLocationRelativeTo(null);
    }
    InfoIndex(){
        AllInDex();
    }

}

class ChgStudent{
    public static int chgStudent(Student student){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        studentDao.updateStudent(student);
        sqlSession.commit();
        sqlSession.close();
        return 1;
    }
}

class ChgCourse{
    public static int chgCourse(Course course){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        CourseDao courseDao = sqlSession.getMapper(CourseDao.class);
        courseDao.updateCourse(course);
        sqlSession.commit();
        sqlSession.close();
        return 1;
    }
}

class ChgSc{
    public static int chgSc(Sc sc) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        ScDao scDao = sqlSession.getMapper(ScDao.class);
        scDao.updateSc(sc);
        sqlSession.commit();
        sqlSession.close();
        return 1;
    }
}